package com.baizhi.aspect;

import com.baizhi.annotation.LogAnno;
import com.baizhi.entity.Admin;
import com.baizhi.entity.Log;
import com.baizhi.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * 日志环绕通知类
 */
@Aspect//表明是一个切面类
@Configuration //将配置类交给工厂管理
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
    @Autowired
    HttpServletRequest request;
    @Autowired
    private LogService logService;

    @Around("@annotation(com.baizhi.annotation.LogAnno)")
    public Object around(ProceedingJoinPoint joinPoint){
        System.out.println("---------进入环绕通知-------");

        //谁 时间 操作  成功
        Admin admin = (Admin)request.getServletContext().getAttribute("admin");
        String username = admin.getUsername();
        //String username = "ssss";

        //操作的方法名
        String nethodName = joinPoint.getSignature().getName();

        //获取方法的Signature对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        //获取方法
        Method method = signature.getMethod();

        //获取方法上的注解
        LogAnno addlog = method.getAnnotation(LogAnno.class);

        //获取注解上的属性值
        String value = addlog.name();

        String status=null;
        Object result = null;

        try {
            //放行通知执行目标方法
            result = joinPoint.proceed();
            status="Success(执行成功)";
        } catch (Throwable e) {
            status="Error(执行失败)";
            System.out.println("-------------进入异常--------");
            throw new RuntimeException(e.getMessage());
        }finally {
            Log logs = new Log(null, username, new Date(), nethodName+"( "+value+" )", status);
            log.info("logs : {}",logs);
            logService.insert(logs);
            System.out.println("------------添加------------");
        }
        return result;
    }
}
